package com.jss.lanouhn.fristapp.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jss.lanouhn.fristapp.R;
import com.jss.lanouhn.fristapp.activity.SearchActivity;
import com.jss.lanouhn.fristapp.adapters.PopViewAdapter;
import com.jss.lanouhn.fristapp.adapters.ViewPagerAdapter;
import com.jss.lanouhn.fristapp.fragments.homeChirdFragment.Base10Fragment;
import com.jss.lanouhn.fristapp.fragments.homeChirdFragment.Base11Fragment;
import com.jss.lanouhn.fristapp.fragments.homeChirdFragment.Base1Fragment;
import com.jss.lanouhn.fristapp.fragments.homeChirdFragment.Base2Fragment;
import com.jss.lanouhn.fristapp.fragments.homeChirdFragment.Base3Fragment;
import com.jss.lanouhn.fristapp.fragments.homeChirdFragment.Base4Fragment;
import com.jss.lanouhn.fristapp.fragments.homeChirdFragment.Base5Fragment;
import com.jss.lanouhn.fristapp.fragments.homeChirdFragment.Base6Fragment;
import com.jss.lanouhn.fristapp.fragments.homeChirdFragment.Base7Fragment;
import com.jss.lanouhn.fristapp.fragments.homeChirdFragment.Base8Fragment;
import com.jss.lanouhn.fristapp.fragments.homeChirdFragment.Base9Fragment;
import com.jss.lanouhn.fristapp.fragments.homeChirdFragment.BaseFragment;
import com.jss.lanouhn.fristapp.fragments.homeChirdFragment.Home_chose_fragment;
import com.jss.lanouhn.fristapp.modles.TabNames;
import com.jss.lanouhn.fristapp.utils.ScreenUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lanouhn on 16/8/23.
 */
public class Fragment_Home extends Fragment {
    private ImageView iv2, iv_search;
    private PopupWindow popupWindow;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private List<String> tabNames;
    private List<Fragment> fragments;
    private ViewPagerAdapter adapter;
    private TabNames names;
    private GridView gridView;
    private PopViewAdapter adapterPop;
    private TextView tv_fragment_home;
    private String url = "http://api.liwushuo.com/v2/channels/preset?gender=1&generation=2";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        iv2 = (ImageView) getView().findViewById(R.id.ic_conutry_btn);
        iv_search = (ImageView) getView().findViewById(R.id.iv_bar_seacher);
        tabLayout = (TabLayout) getView().findViewById(R.id.tl_home);
        viewPager = (ViewPager) getView().findViewById(R.id.vp_home);
        tv_fragment_home = (TextView) getView().findViewById(R.id.tv_fragment_home);



        initData();
        initPopWindows();
        initDataName();
        initEvent();
    }

    private void initData() {
        //整理TabLayout的数据
        tabNames = new ArrayList<>();
        tabNames.add("精选");
        tabNames.add("送女票");
        tabNames.add("海淘");
        tabNames.add("创意生活");
        tabNames.add("送基友");
        tabNames.add("送爸妈");
        tabNames.add("送同事");
        tabNames.add("送宝贝");
        tabNames.add("设计感");
        tabNames.add("文艺风");
        tabNames.add("奇葩搞怪");
        tabNames.add("科技范");
        tabNames.add("萌萌哒");

        //整理ViewPager的数据集合
        fragments = new ArrayList<>();

        fragments.add(new Home_chose_fragment());
        fragments.add(new BaseFragment());
        fragments.add(new Base1Fragment());
        fragments.add(new Base2Fragment());
        fragments.add(new Base3Fragment());
        fragments.add(new Base4Fragment());
        fragments.add(new Base5Fragment());
        fragments.add(new Base6Fragment());
        fragments.add(new Base7Fragment());
        fragments.add(new Base8Fragment());
        fragments.add(new Base9Fragment());
        fragments.add(new Base10Fragment());
        fragments.add(new Base11Fragment());

        adapter = new ViewPagerAdapter(getChildFragmentManager(), fragments, tabNames);
        viewPager.setAdapter(adapter);
        //tablayout和viewPager的绑定
        tabLayout.setupWithViewPager(viewPager);

        viewPager.setOffscreenPageLimit(13);
    }


    private void initDataName() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Gson gson = new Gson();
                        names = gson.fromJson(result, TabNames.class);
                        if (names.getData().getChannels().size() > 0) {
                            handler.sendEmptyMessage(1);
                        } else {
                            Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    adapterPop = new PopViewAdapter(names, getContext());
                    gridView.setAdapter(adapterPop);
                    break;
            }
        }
    };


    private void initPopWindows() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.pull_popwindows, null);
        gridView = (GridView) view.findViewById(R.id.rv_pop_pull);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //通过操作getItem这个方法来得到

//                View view2 = gridView.getChildAt(position).findViewById(R.id.view_item_only_text);
//                view2.setVisibility(View.VISIBLE);
//                tabNames.get(position);
                adapterPop.setSelectItem(position);
                adapterPop.notifyDataSetChanged();
                tabLayout.setVisibility(View.VISIBLE);
                tv_fragment_home.setVisibility(View.GONE);
                popupWindow.dismiss();
                viewPager.setCurrentItem(position);

            }
        });
        //通过view 和宽·高，构造PopopWindow
        popupWindow = new PopupWindow(view, ScreenUtils.getScreenWidth(getContext()), 240, false);
        //此处为popwindow 设置背景，同事做到点击外部区域，popwindow消失
        popupWindow.setBackgroundDrawable(getActivity().getResources().getDrawable(R.mipmap.scratch_bg));
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(true);
        //刷新状态
        popupWindow.update();
        //设置焦点为可点击
        popupWindow.setFocusable(true);
    }

    private void initEvent() {
        iv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //将window视图显示在icon_top下面
                popupWindow.showAsDropDown(tabLayout);
                iv2.setImageResource(R.mipmap.country_code_select_btn_up);
                tabLayout.setVisibility(View.INVISIBLE);
                tv_fragment_home.setVisibility(View.VISIBLE);


            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                adapterPop.setSelectItem(position);
                adapterPop.notifyDataSetChanged();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                iv2.setImageResource(R.mipmap.country_code_select_btn_down);
                tabLayout.setVisibility(View.VISIBLE);
                tv_fragment_home.setVisibility(View.GONE);
            }
        });
        iv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            }
        });
    }


}
